/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/njzf/znids">JeeSite</a> All rights reserved.
 */
package com.zf.bm.common.core.sys.utils;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zf.bm.common.constant.Constant;
import com.zf.bm.common.core.sys.dao.DictDao;
import com.zf.bm.common.core.sys.entity.Dict;
import com.zf.bm.common.utils.CacheUtils;
import com.zf.bm.common.utils.SpringContextHolder;
import com.zf.bm.common.utils.mapper.JsonMapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 字典工具类
 *
 * @author ThinkGem
 * @version 2013-5-29
 */
public class DictUtils {
    private DictUtils() {
    }

    private static DictDao dictDao = SpringContextHolder.getBean(DictDao.class);

    public static final String CACHE_DICT_MAP = "dictMap";
    private static final String DEL_FLAG = "del_flag";
    private static final String TYPE = "type";

    public static String getDictLabel(String value, String type, String defaultValue) {
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)) {
            for (Dict dict : getDictList(type)) {
                if (type.equals(dict.getType()) && value.equals(dict.getValue())) {
                    return dict.getLabel();
                }
            }
        }
        return defaultValue;
    }

    public static String getDictLabels(JSONArray values, String type, String defaultValue) {
        if (StringUtils.isNotBlank(type) && !values.isEmpty()) {
            List<String> valueList = Lists.newArrayList();
            for (int i = 0; i < values.size(); i++) {
                valueList.add(getDictLabel(values.get(i).toString(), type, defaultValue));
            }
            return StringUtils.join(valueList, ",");
        }
        return defaultValue;
    }

    public static String getDictValue(String label, String type, String defaultLabel) {
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)) {
            for (Dict dict : getDictList(type)) {
                if (type.equals(dict.getType()) && label.equals(dict.getLabel())) {
                    return dict.getValue();
                }
            }
        }
        return defaultLabel;
    }

    public static List<Dict> getDictList(String type) {
        @SuppressWarnings("unchecked")
        Map<String, List<Dict>> dictMap = (Map<String, List<Dict>>) CacheUtils.get(CACHE_DICT_MAP);
        if (dictMap == null) {
            dictMap = Maps.newHashMap();
            for (Dict dict : dictDao.selectList(new QueryWrapper<Dict>().orderByAsc(TYPE, "sort", "update_date").eq(DEL_FLAG, "0"))) {
                List<Dict> dictList = dictMap.get(dict.getType());
                if (dictList != null) {
                    dictList.add(dict);
                } else {
                    dictMap.put(dict.getType(), Lists.newArrayList(dict));
                }
            }
            CacheUtils.put(CACHE_DICT_MAP, dictMap);
        }
        List<Dict> dictList = dictMap.get(type);
        if (dictList == null) {
            dictList = Lists.newArrayList();
        }
        return dictList;
    }

    /**
     * 返回字典列表（JSON）
     *
     * @param type
     * @return
     */
    public static String getDictListJson(String type) {
        return JsonMapper.toJsonString(getDictList(type));
    }


    /**
     * 获取字典的类型
     *
     * @param type
     * @return
     */
    public static List<Map<String, String>> getDicTypeList(String type) {
        List<Dict> dictList = dictDao.selectList(new QueryWrapper<Dict>().eq(DEL_FLAG, "0"));
        List<Map<String, String>> mapList = new LinkedList<>();
        List<String> typeList = dictList.stream().map(Dict::getType).distinct().collect(Collectors.toList());
        String[] array = typeList.toArray(new String[]{});
        Arrays.sort(array, String.CASE_INSENSITIVE_ORDER);
        for (String s : array) {
            Map<String, String> map = new HashMap<>();
            map.put("value", s);
            map.put("label", s);
            map.put(TYPE, type);
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 根据类型获取值
     *
     * @param type 唯一
     * @return
     */
    public static String getDictValueByType(String type) {
        List<Dict> list = dictDao.selectList(new QueryWrapper<Dict>()
                .eq(DEL_FLAG, "0")
                .eq(TYPE, type));
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0).getValue();
    }

    /**
     * 自动化开关是否打开
     * on：开；off：关，默认关
     * @return
     */
    public static boolean isAutoTest() {
        // 自动化测试开关，on：开；off：关，默认关
        String value = DictUtils.getDictValueByType(Constant.AUTOMATED_TEST_SWITCH_TYPE);
        return Constant.AUTOMATED_TEST_SWITCH_ON.equals(value);
    }
}
